﻿using System.Text;

namespace PLMonitor;

// 0空闲 1单发 2连发 3泄放 4记录 5自检
internal class GUNControl
{
    #region 成员变量
    public float V1 { get; set; }
    public float V2 { get; set; }
    public float V3 { get; set; }

    public bool IsModeSetOk { get; set; } = false;
    public bool IsEnergySetOk { get; set; } = false;

    public bool IsModeGetOk { get; set; } = false;
    public bool IsEnergyGetOk { get; set; } = false;

    public int Mode { get; set; } = -1;
    public int Energy { get; set; } = -1;
    #endregion

    public bool ProcRcvData(byte[] data, int count)
    {
        // #write mode set succeed!\r\n
        // #write energy set succeed!\r\n
        // #cap_vol=240,0,54,0,0,0,0,0\r\n
        var ret = Encoding.UTF8.GetString(data, 0, count);
        if (string.IsNullOrEmpty(ret))
        {
            return false;
        }

        if (ret.Contains("#write mode set succeed!"))
        {
            IsModeSetOk = true;
        }

        if (ret.Contains("#write energy set succeed!"))
        {
            IsEnergySetOk = true;
        }

        if (ret.Contains("#cap_vol="))
        {
            var idx = ret.IndexOf('=');
            if (idx > 0)
            {
                var strVal = ret[idx..].TrimEnd( Environment.NewLine.ToCharArray());
                var segs = strVal.Split(',');
                // 返回8路电压，将第3 - 5路电压显示在电压显示区域
                if (segs.Length >= 8)
                {
                    try
                    {
                        V1 = float.Parse(segs[2]);
                        V2 = float.Parse(segs[3]);
                        V3 = float.Parse(segs[4]);
                    }
                    catch
                    {
                        // 忽略
                    }
                }
            }
        }

        if (ret.Contains("#mode="))
        {
            var idx = ret.IndexOf('=') + 1;            
            var strVal = ret.Substring(idx, 1);
            strVal = strVal.Replace(';', ' ');
            Mode = int.Parse(strVal);
            IsModeGetOk = true;
        }

        if (ret.Contains("#energy="))
        {
            var idx = ret.IndexOf('=') + 1;
            var strVal = ret.Substring(idx, 1);
            Energy = int.Parse(strVal);
            IsEnergyGetOk = true;
        }
        return true;
    }
}
